package sketch.generator;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import sketch.util.Checker;

public class SequentialLink implements IIterationLink {
	
	private List<IGenerator<?>> innerGenerators = new LinkedList<IGenerator<?>>();
	
	private Iterator<IGenerator<?>> generatorIterator = null;
	
	private IGenerator<?> currentGenerator = null;
	
	private Object current = null;

	public SequentialLink(List<IGenerator<?>> generators) {
		Checker.checkNull(generators, "generators for SequentialLink could not be null");
		for(IGenerator<?> generator : generators) {
			Checker.checkNull(generator, "generator could not be null!");
			innerGenerators.add(generator);
		}
	}
	
	@Override
	public boolean hasNext() {
		if(generatorIterator == null) {
			this.generatorIterator = this.innerGenerators.iterator();
			if(!this.generatorIterator.hasNext()) {
				return false;
			}
			this.currentGenerator = this.generatorIterator.next();
		}
		
		if(this.currentGenerator == null) {
			//acutally, it is the buggy condition
			return false;
		}
		
		while(!this.currentGenerator.hasNext()) {
			if(!this.generatorIterator.hasNext()) {
				return false;
			}
			this.currentGenerator = this.generatorIterator.next();
		}
		
		return true;
	}

	@Override
	public void next() {
		if(!hasNext()) {
			throw new IterationException("No more element in Sequential link!");
		}
		this.current = this.currentGenerator.next();
	}

	@Override
	public void reset() {
		this.generatorIterator = null;
		this.currentGenerator = null;
		this.current = null;
	}
	
	public Object current() {
		return this.current;
	}

}
